package com.example.zhengsr.surfaceboard.socket;


import android.util.Log;

import com.example.zhengsr.surfaceboard.Constans;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UdptestProvider extends Thread {
    private static final String TAG = "UdpProvider";
    private boolean isFinish = false;
    private DatagramSocket socket;
    @Override
    public void run() {
       // super.run();
        Log.d(TAG, "zsr run: ");
        try {
            socket = new DatagramSocket(Constans.PORT);
            while(!isFinish) {
                Log.d(TAG, "zsr 我已准备好");
                byte[] buf = new byte[1024];
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                socket.receive(packet);

                String ip = packet.getAddress().getHostAddress();
                int port = packet.getPort();
                int length = packet.getLength();
                String msg = new String(buf, 0, length);
                Log.d(TAG, "zsr 客户端: " + ip + "\tport: " + port + "\t信息: " + msg);

                /**
                 * 发送消息给客户端
                 */

                byte[] receiveBuf = "我是Android设备".getBytes();
                DatagramPacket receivePacket = new DatagramPacket(
                        receiveBuf,
                        receiveBuf.length,
                        packet.getAddress(),
                        Constans.BROADCAST_PORT
                );

                socket.send(receivePacket);
            }
           // socket.close();


        } catch (Exception e) {
            //e.printStackTrace();
        }finally {
            exit();
        }
    }
    public void exit(){
        isFinish = true;
        if (socket != null){
            socket.close();
            socket = null;
        }
    }
}
